import { listDictDataType } from '@/api/system/dict.data.service'

/**
 * 根据字典类型获取字典数据
 * @param {*} dictTypeList 
 * mdGetDictData(['sys_user_sex', 'sys_show_hide', 'sys_normal_disable']).then(res => {
 *   console.log(res)
 * })
 */
export const mdGetDictData = (dictTypeList = [], source = 'dict') => {
  if (source === 'dict') {
    return new Promise((resolve, reject) => {
      try {
        const result = {}

        dictTypeList.forEach(key => { result[key] = [] })

        const promiseAll = []

        if (dictTypeList && dictTypeList.length > 0) {
          dictTypeList.forEach(type => {
            promiseAll.push(listDictDataType(type))
          })
        }

        if (promiseAll && promiseAll.length > 0) {
          Promise.all(promiseAll).then(res => {
            const data = []

            res.forEach(item => {
              if (item.data && item.data.length > 0) {
                data.push(...item.data)
              }
            })

            if (data && data.length > 0) {
              data.forEach(item => {
                if (Object.keys(result).includes(item.dictType)) {
                  result[item.dictType].push(item)
                }
              })
            }

            resolve(result)
          }).catch(error => {
            console.log(error)
            reject(error)
          })
        }
      } catch (error) {
        console.log(error)
        reject(error)
      }
    })
  }
}